package com.book.controller;

import com.book.utils.CodeTool;
import com.book.utils.RedisCache;
import com.book.utils.ResponseResult;
import com.book.utils.SendMailTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
/**
 * @author yicheng
 */
//匿名访问
@RestController
public class EmailController{
    @Autowired
    private SendMailTool sendMailTool;
    @Autowired
    private RedisCache redisCache;

    /**
     *
     * @param email 邮箱账号
     * @return 统一返回格式，正确的code统一为200
     */
    @GetMapping("/getCaptcha")
    public ResponseResult getCaptcha(@RequestParam String email){//获取验证码用的
//        System.out.println(email);
        String captcha = CodeTool.getCaptcha();//获取随机生成的一个验证码
        //将邮箱验证码暂时保存在redis中，时间为5min
        redisCache.setCacheObject(email,captcha,300, TimeUnit.SECONDS);
        try {
            sendMailTool.SendMail(email, captcha);//调用方法来发送邮件
            return new ResponseResult(200,"验证码发送成功，请查看邮箱!");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(1002,"邮件发送失败，请重试!");
        }
    }
}
